<template>
    <div>
        <div>
            <button @click="recordNumber" class="search-button">用户录入数量可视化</button>
            <button @click="dateRecordNumber" class="search-button2">录入日期数量可视化</button>
            <button @click="showTotalPriceChart" class="totalPrice-button">总金额可视化</button>
            <button @click="showInvoiceNumberChart" class="invoiceNumber-button">发票录入数量可视化</button>
        </div>
        <!-- 可视化图表容器 -->
        <div v-if="showChart" id="chart" style="width: 100%; height: 400px;"></div>
    </div>
</template>

<script>
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import axios from 'axios'; // 引入 axios
import * as echarts from 'echarts'; // 引入 ECharts

export default {
    data() {
        return {
            invoiceData: [],
            displayColumns: ['发票编号', '录入用户名', '录入日期', '操作'],
            currentPage: 1,
            pageSize: 10,
            searchQuery: '', // 查询条件
            filteredInvoiceData: [], // 过滤后的数据
            paginatedData: [], // 分页后的数据
            showChart: false // 控制图表是否显示
        };
    },
    created() {
        this.fetchInvoices();
    },
    methods: {
        fetchInvoiceData() {
        // 发送 HTTP 请求获取 invoice 表数据
        axios.get('http://127.0.0.1:5000/api/invoice_data')
        .then(response => {
            this.invoiceData = response.data;
            this.filterData(); // 初始加载时也进行过滤
            })
        .catch(error => {
            console.error('获取数据出错:', error);
            });
        },
        async fetchInvoices() {
            try {
                const response = await axios.get('http://127.0.0.1:5000/api/record_data'); // 使用 axios 替换 fetch
                this.invoiceData = response.data;
                this.filterData(); // 初始加载时也进行过滤
            } catch (error) {
                console.error('Failed to fetch invoices:', error);
            }
        },
        handleDelete(no) {
            const shouldDelete = window.confirm('您是否要删除？');
            if (shouldDelete) {
                this.deleteRow(no);
            }
        },
        deleteRow(no) {
            console.log("要发送的 No 值:", no);  // 添加这行日志
            // 向后端发送删除请求
            axios.post('http://127.0.0.1:5000/api/delete_record', { no })
              .then(response => {
                    if (response.data.success) {
                        // 如果删除成功，重新获取数据
                        this.fetchInvoices();
                    } else {
                        console.error('删除失败:', response.data.message);
                    }
                })
              .catch(error => {
                    console.error('删除请求出错:', error);
                });
        },
        editRow(index) {
            // 这里应实现与后端交互以进行修改操作
            // 示例：仅在控制台输出要修改的行索引
            console.log('修改第', index, '行');
        },
        handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.paginateData();
        },
        handleCurrentChange(newPage) {
            this.currentPage = newPage;
            this.paginateData();
        },
        filterData() {
            // 根据查询条件过滤数据
            if (!this.searchQuery) {
                this.filteredInvoiceData = this.invoiceData; // 如果没有查询条件，显示全部数据
            } else {
                const query = this.searchQuery.toLowerCase();
                this.filteredInvoiceData = this.invoiceData.filter(row => {
                    // 检查每一行的每个字段是否包含查询内容
                    return row.some(value => {
                        return String(value).toLowerCase().includes(query);
                    });
                });
            }
            this.paginateData();
        },
        paginateData() {
            const startIndex = (this.currentPage - 1) * this.pageSize;
            const endIndex = startIndex + this.pageSize;
            this.paginatedData = this.filteredInvoiceData.slice(startIndex, endIndex);
        },
        recordNumber() {
            this.showChart = true;
            this.$nextTick(() => {
                // 统计每个录入用户名的发票数量
                const userCountMap = {};
                this.invoiceData.forEach(row => {
                    const username = row[1];
                    if (userCountMap[username]) {
                        userCountMap[username]++;
                    } else {
                        userCountMap[username] = 1;
                    }
                });
                // 将统计结果转换为数组并按录入数量从高到低排序
                const userCountArray = Object.entries(userCountMap).sort((a, b) => b[1] - a[1]);
                const usernames = userCountArray.map(item => item[0]);
                const counts = userCountArray.map(item => item[1]);

                // 初始化 ECharts 实例
                const chartDom = document.getElementById('chart');
                const myChart = echarts.init(chartDom);
                const option = {
                    xAxis: {
                        type: 'category',
                        data: usernames,
                        axisLabel: {
                            rotate: 45, // 横坐标标签旋转 45 度，避免标签重叠
                            interval: 0 // 强制显示所有标签
                        }
                    },
                    yAxis: {
                        type: 'value',
                        minInterval: 1 // 设置 Y 轴单位间隔为 1
                    },
                    series: [{
                        data: counts,
                        type: 'bar'
                    }]
                };
                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);
            });
        },
        dateRecordNumber() {
            this.showChart = true;
            this.$nextTick(() => {
                // 统计每个录入日期的发票数量
                const dateCountMap = {};
                this.invoiceData.forEach(row => {
                    const date = row[2];
                    if (dateCountMap[date]) {
                        dateCountMap[date]++;
                    } else {
                        dateCountMap[date] = 1;
                    }
                });
                // 将统计结果转换为数组并按日期排序
                const dateCountArray = Object.entries(dateCountMap).sort((a, b) => new Date(a[0]) - new Date(b[0]));
                const dates = dateCountArray.map(item => item[0]);
                const counts = dateCountArray.map(item => item[1]);

                // 初始化 ECharts 实例
                const chartDom = document.getElementById('chart');
                const myChart = echarts.init(chartDom);
                const option = {
                    xAxis: {
                        type: 'category',
                        data: dates,
                        axisLabel: {
                            rotate: 45, // 横坐标标签旋转 45 度，避免标签重叠
                            interval: 0 // 强制显示所有标签
                        }
                    },
                    yAxis: {
                        type: 'value',
                        minInterval: 1 // 设置 Y 轴单位间隔为 1
                    },
                    series: [{
                        data: counts,
                        type: 'bar'
                    }]
                };
                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);
            });
        },
        showTotalPriceChart() {
            const goodsTotalPrice = {};
            this.invoiceData.forEach(row => {
                const goodsName = row[2];
                const price = parseFloat(row[3]);
                const quantity = parseFloat(row[4]);
                if (!isNaN(price) &&!isNaN(quantity)) {
                const totalPrice = price * quantity;
                if (goodsTotalPrice[goodsName]) {
                    goodsTotalPrice[goodsName] += totalPrice;
                } else {
                    goodsTotalPrice[goodsName] = totalPrice;
                }
                }
            });

            const goodsNames = Object.keys(goodsTotalPrice);
            const totalPrices = Object.values(goodsTotalPrice);

            const chartDom = document.getElementById('totalPriceChart');
            const myChart = echarts.init(chartDom);
            const option = {
                title: {
                text: '每种货物的总金额'
                },
                xAxis: {
                type: 'category',
                data: goodsNames,
                name: '货物名称'
                },
                yAxis: {
                type: 'value',
                name: '总金额'
                },
                series: [{
                data: totalPrices,
                type: 'bar',
                itemStyle: {
                    color: '#62dec9'
                }
                }]
            };

            option && myChart.setOption(option);
        },
        showInvoiceNumberChart() {
            const invoiceCountByDate = {};
            this.invoiceData.forEach(row => {
                const invoiceDate = row[1];
                if (invoiceCountByDate[invoiceDate]) {
                invoiceCountByDate[invoiceDate]++;
                } else {
                invoiceCountByDate[invoiceDate] = 1;
                }
            });

            const invoiceDates = Object.keys(invoiceCountByDate);
            const invoiceCounts = Object.values(invoiceCountByDate);

            const chartDom = document.getElementById('invoiceNumberChart');
            const myChart = echarts.init(chartDom);
            const option = {
                title: {
                text: '按开票日期的发票录入数量'
                },
                xAxis: {
                type: 'category',
                data: invoiceDates,
                // axisLabel: {
                //     rotate: 45, // 横坐标标签旋转 45 度，避免标签重叠
                //     interval: 0 // 强制显示所有标签
                // },
                name: '开票日期'
                },
                yAxis: {
                type: 'value',
                name: '发票数量'
                },
                series: [{
                data: invoiceCounts,
                type: 'bar',
                itemStyle: {
                    color: '#3db0d9'
                }
                }]
            };

            option && myChart.setOption(option);
        }
    },
    watch: {
        // 监听搜索框内容变化，实时过滤数据
        searchQuery(newQuery) {
            this.filterData();
        }
    }
};
</script>

<style scoped>
table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    border: 1px solid #ccc;
    padding: 8px;
    text-align: left;
}

th {
    background-color: #f2f2f2;
}

.delete-button {
    background-color: #e9120a;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 10px;
}

.modify-button {
    background-color: #4273b3;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 10px;
}

.search-input {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-right: 10px;
    font-size: 14px;
    width: 300px; /* 可以根据需要调整宽度 */
}

.search-button {
    background-color: #28a745;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    margin-left: 10px; /* 添加左边距，让按钮之间有间距 */
}

.search-button2 {
    background-color: #4fa3cd;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    margin-left: 10px; /* 添加左边距，让按钮之间有间距 */
}

.totalPrice-button {
  background-color: #62dec9;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
}

.invoiceNumber-button {
  background-color: #3db0d9;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
}
</style>    